import {computed, onMounted, reactive, ref, watch, onUnmounted} from "vue";
import {useRoute, useRouter} from "vue-router";

import {delay} from "@/utils/delay";
import scssVariables from '../var.scss'
import {events} from "@/utils/event";

const usePageNavAnchor = (props: any) => {
  const contentRef = ref(null);
  const state = reactive({
    navList: [] as { top: number, name: string; }[],
    scrollTop: 0
  });
  const activeNavIndex = computed(() => {
    // console.log('activeNavIndex--- --- ---');
    for (let i = state.navList.length - 1; i >= 0; i--) {
      const navItem = state.navList[i];
      if (state.scrollTop >= navItem.top - parseInt(scssVariables.headerHeight)) {
        return i;
      }
    }

    return 0;
  });

  const refreshNavList = () => {
    // console.log('refreshNavList--- --- ---');
    const target = contentRef.value;
    if (!target) return;
    const h2List = Array.from((target as HTMLElement).querySelectorAll('h2'));
    state.navList = h2List.map((h2, index) => {
      let {offsetTop, innerText} = h2;
      innerText = innerText.replace(/在线调试.*/, '').trim();
      return {
        top: index === 0 ? 0 : offsetTop,
        name: innerText
      }
    })
      .filter(item => !!item.name);
    // console.log('state.navList:', state.navList);
    scrollByHash(route.hash);
  };
  const onScrollTop = () => {
    // console.log('onScrollTop--- --- ---');
    // console.log('document.documentElement.scrollTop:',document.documentElement.scrollTop);
    state.scrollTop = document.documentElement.scrollTop;
  };
  onMounted(async () => {
    window.addEventListener('scroll', onScrollTop);

    //mdc-case里 processHtmlString 是异步处理的, 故这里要delay一下
    //不然navList获取到的top只要涉及到case的,都是不准确
    // await delay(150);
    // refreshNavList();
  });
  const route = useRoute();
  const router = useRouter();
  const onClickNavItem = (name: string) => {
    router.push({
      path: route.path,
      hash: '#' + name
    });
  };
  const scrollByHash = (hash: string) => {
    // console.log('scrollByHash--- --- ---');
    // console.log('hash:', hash);
    if (hash.startsWith('#')) hash = hash.slice(1);
    if (!hash) {
      if (!!state.navList && state.navList.length > 0) {
        hash = state.navList[0].name
      }
    }
    // 页面锚点定位
    for (let i = 0; i < state.navList.length; i++) {
      const navItem = state.navList[i];
      if (navItem.name === hash) {
        return scrollTop(navItem.top - parseInt(scssVariables.headerHeight) );
      }
    }
  };
  const scrollTop = (top: number) => {
    // console.log('scrollTop--- --- ---');
    // console.log('top:',top);
    document.documentElement.scrollTop = top
  };
  watch(() => route.hash, async (val) => {
    scrollByHash(val);
  });

  //todo 如果传递的是组件作为content展示, 这里这样就不对了
  /*watch(() => props.content, async () => {
    await delay(300); //原因同上
    refreshNavList();
  });*/
  events.on('page-ready', refreshNavList);
  onUnmounted(()=>{
    events.off('page-ready', refreshNavList);
  })

  return {
    contentRef,
    state,
    activeNavIndex,
    onClickNavItem
  }
};

export {
  usePageNavAnchor
};

export default usePageNavAnchor;
